package com.victualler.core.common.io;



import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class InterfaceOutputStream extends ServletOutputStream {
    private HttpServletResponse response;
    private ByteArrayOutputStream byteArrayOutputStream;

    public InterfaceOutputStream(HttpServletResponse response) {
        this.response = response;
        this.byteArrayOutputStream = new ByteArrayOutputStream();
    }

    public String getResult(String charset) throws UnsupportedEncodingException {
        return this.byteArrayOutputStream.toString(charset);
    }

    public String getResult() throws UnsupportedEncodingException {
        return this.byteArrayOutputStream.toString();
    }
    public void close() throws IOException {
        String result = this.byteArrayOutputStream.toString("utf-8");
        ServletOutputStream outputStream = this.response.getOutputStream();
        outputStream.write(result.getBytes("utf-8") );
        outputStream.close();
    }

    public boolean isReady() {
        return false;
    }

    public void setWriteListener(WriteListener writeListener) {
    }

    public void write(int b) throws IOException {
        this.byteArrayOutputStream.write(b);
    }

    public ByteArrayOutputStream getByteArrayOutputStream() {
        return byteArrayOutputStream;
    }
}
